﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace UI
{
    /// <summary>
    /// 导航精灵页面
    /// </summary>
    public class FuncNavPage : Page
    {
        public SimpleGrid grid;
        public UIScrollView scrollView;
        public GameObject noneTip;
        public GameObject haveTip;

        public GameObject funcNavItemPrefab;

        public FuncNavAudioCtrl audioCtrl;


        void Start()
        {
        }

        protected override void DoOpen()
        {

            ProtoBuf.Message.CSNavigationItem msg = new ProtoBuf.Message.CSNavigationItem();
            NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSNavigationItem, msg, (pack, b) => {
                if (b)
                {
                    StaticData.funcNavKit.FuncNavCallback(pack.kBody);
                    Refresh();
                }
            });
            audioCtrl.Play();
        }

        void Refresh()
        {
            foreach (var item in grid.childs)
            {
                Destroy(item);
            }
            grid.childs.Clear();

            if (StaticData.funcNavKit.IsFuncNavHaveTip())
            {
                haveTip.SetActive(true);
                noneTip.SetActive(false);
                List<GameObject> items = new List<GameObject>();
                foreach (var item in StaticData.funcNavKit.enableFuncs)
                {
                    GameObject obj = GameObject.Instantiate(funcNavItemPrefab) as GameObject;
                    obj.GetComponent<FuncNavItem>().Init(item, this);
                    items.Add(obj);
                }
                items.Sort((GameObject x, GameObject y) => {
                    return x.GetComponent<FuncNavItem>().GetSortIndex().CompareTo(y.GetComponent<FuncNavItem>().GetSortIndex());
                });
                foreach (var item in items)
                {
                    grid.AddChild(item);
                }
                scrollView.ResetPosition();
            }
            else
            {
                haveTip.SetActive(false);
                noneTip.SetActive(true);
            }
        }

        void OnFuncNavDataUpdate()
        {
            Refresh();
        }

    }
}